#include "unifiedgamerenderer.h"
#include <QDebug>
#include <QDateTime>

UnifiedGameRenderer::UnifiedGameRenderer(QObject *parent)
    : QObject(parent)
    , m_stateProcessor(nullptr)
    , m_renderThread(nullptr)
    , m_currentMode(GameMode::SinglePlayer)
    , m_running(false)
    , m_paused(false)
    , m_hasServerState(false)
    , m_performanceTimer(new QTimer(this))
    , m_lastStatsUpdate(0)
    , m_threadsRunning(false)
    , m_threadFailureCount(0)
{
    // 注册自定义类型
    qRegisterMetaType<UnifiedGameRenderer::PerformanceStats>("UnifiedGameRenderer::PerformanceStats");

    initializeComponents();
    setupConnections();

    qDebug() << "UnifiedGameRenderer: 统一渲染器初始化完成";
}

UnifiedGameRenderer::~UnifiedGameRenderer()
{
    stopGame();
    qDebug() << "UnifiedGameRenderer: 统一渲染器已销毁";
}

void UnifiedGameRenderer::initializeComponents()
{
    // 创建游戏状态处理器
    m_stateProcessor = new GameStateProcessor(this);

    // 创建渲染线程
    m_renderThread = new RenderThread(this);

    // 设置性能监控定时器
    m_performanceTimer->setInterval(1000); // 每秒更新一次
    connect(m_performanceTimer, &QTimer::timeout, this, &UnifiedGameRenderer::onPerformanceTimer);

    qDebug() << "UnifiedGameRenderer: 核心组件初始化完成";
}

void UnifiedGameRenderer::setupConnections()
{
    qDebug() << "UnifiedGameRenderer: 开始设置信号连接";
    qDebug() << "  m_stateProcessor 存在:" << (m_stateProcessor != nullptr);
    qDebug() << "  m_renderThread 存在:" << (m_renderThread != nullptr);

    // 连接游戏状态处理器
    bool connection1 = connect(m_stateProcessor, &GameStateProcessor::renderDataReady,
                              this, &UnifiedGameRenderer::onRenderDataReady, Qt::QueuedConnection);
    qDebug() << "  renderDataReady 连接结果:" << connection1;

    bool connection2 = connect(m_stateProcessor, &GameStateProcessor::gameEnded,
                              this, &UnifiedGameRenderer::onGameEnded, Qt::QueuedConnection);
    qDebug() << "  gameEnded 连接结果:" << connection2;

    // 连接渲染线程
    bool connection3 = connect(m_renderThread, &RenderThread::frameReady,
                              this, &UnifiedGameRenderer::onFrameReady, Qt::QueuedConnection);
    qDebug() << "  frameReady 连接结果:" << connection3;

    // 连接渲染线程FPS到外部UI
    bool connection4 = connect(m_renderThread, &RenderThread::fpsUpdated,
                               this, [this](int fps){
                                   QMutexLocker locker(&m_statsMutex);
                                   m_stats.currentFPS = fps;
                                   emit fpsChanged(fps);
                               }, Qt::QueuedConnection);
    qDebug() << "  fpsUpdated 连接结果:" << connection4;

    qDebug() << "UnifiedGameRenderer: 信号连接设置完成";
}

void UnifiedGameRenderer::startGame(GameMode mode, const RenderConfig &config)
{
    if (m_running) {
        qDebug() << "UnifiedGameRenderer: 游戏已在运行，先停止当前游戏";
        stopGame();
    }

    m_currentMode = mode;
    m_config = config;
    m_running = true;
    m_paused = false;
    // 注意：不重置 m_hasServerState，避免重启时丢失服务器状态
    // m_hasServerState 只在首次收到有效服务器数据时设置为 true
    m_threadFailureCount = 0;

    qDebug() << "UnifiedGameRenderer: 启动游戏";
    qDebug() << "  模式:" << static_cast<int>(mode);
    qDebug() << "  目标FPS:" << config.targetFPS;
    qDebug() << "  渲染尺寸:" << config.renderSize;
    qDebug() << "  启用特效:" << config.enableEffects;

    // 应用配置
    if (m_renderThread) {
        m_renderThread->setRenderSize(config.renderSize);
        // RenderThread不支持setTargetFPS，FPS由内部管理
    }

    // 强制重新连接信号（修复连接断开问题）
    qDebug() << "*** 强制重新连接信号 ***";
    disconnect(m_stateProcessor, nullptr, this, nullptr);
    bool reconnection = connect(m_stateProcessor, &GameStateProcessor::renderDataReady,
                               this, &UnifiedGameRenderer::onRenderDataReady, Qt::QueuedConnection);
    qDebug() << "  renderDataReady 重新连接结果:" << reconnection;

    // 启动线程系统
    startThreads();

    // 启动性能监控
    m_performanceTimer->start();
    m_lastStatsUpdate = QDateTime::currentMSecsSinceEpoch();

    qDebug() << "UnifiedGameRenderer: 游戏启动完成";
}

void UnifiedGameRenderer::stopGame()
{
    if (!m_running) {
        return;
    }

    qDebug() << "UnifiedGameRenderer: 停止游戏";

    m_running = false;
    m_paused = false;

    // 停止性能监控
    m_performanceTimer->stop();

    // 停止线程系统
    stopThreads();

    qDebug() << "UnifiedGameRenderer: 游戏已停止";
}

void UnifiedGameRenderer::pauseGame()
{
    if (!m_running || m_paused) {
        return;
    }

    m_paused = true;
    qDebug() << "UnifiedGameRenderer: 游戏已暂停";
    qDebug() << "  保持服务器状态:" << m_hasServerState;
}

void UnifiedGameRenderer::resumeGame()
{
    if (!m_running || !m_paused) {
        return;
    }

    m_paused = false;
    qDebug() << "UnifiedGameRenderer: 游戏已恢复";
    qDebug() << "  恢复服务器状态:" << m_hasServerState;

    // 如果有服务器状态，立即触发一次渲染更新
    if (m_hasServerState && m_renderThread) {
        qDebug() << "  触发恢复后立即渲染";
        // 通过信号触发渲染线程更新
        QTimer::singleShot(0, this, [this]() {
            if (m_renderThread) {
                // 发送当前数据到渲染线程以刷新显示
                emit frameReady(QPixmap()); // 触发渲染更新
            }
        });
    }
}

void UnifiedGameRenderer::startThreads()
{
    if (m_threadsRunning) {
        return;
    }

    qDebug() << "UnifiedGameRenderer: 启动线程系统";

    bool success = true;

    // 启动游戏状态处理线程
    if (m_stateProcessor) {
        try {
            m_stateProcessor->start();
            // 使用高优先级而非TimeCritical，避免影响系统响应性
            m_stateProcessor->setPriority(QThread::NormalPriority);
            qDebug() << "  游戏状态处理线程已启动（普通优先级）";
        } catch (const std::exception &e) {
            qWarning() << "  游戏状态处理线程启动失败:" << e.what();
            success = false;
        }
    } else {
        qWarning() << "  游戏状态处理器为空";
        success = false;
    }

    // 启动渲染线程
    if (m_renderThread) {
        try {
            m_renderThread->start();
            // 使用高优先级而非TimeCritical，平衡性能和系统响应性
            m_renderThread->setPriority(QThread::NormalPriority);
            qDebug() << "  渲染线程已启动（普通优先级）";
        } catch (const std::exception &e) {
            qWarning() << "  渲染线程启动失败:" << e.what();
            success = false;
        }
    } else {
        qWarning() << "  渲染线程为空";
        success = false;
    }

    if (success) {
        m_threadsRunning = true;
        m_threadFailureCount = 0;
        qDebug() << "  线程系统启动成功";
        qDebug() << "  最终状态检查:";
        qDebug() << "    m_threadsRunning:" << m_threadsRunning;
        qDebug() << "    GameStateProcessor running:" << (m_stateProcessor ? m_stateProcessor->isRunning() : false);
        qDebug() << "    RenderThread running:" << (m_renderThread ? m_renderThread->isRunning() : false);
    } else {
        m_threadFailureCount++;
        qWarning() << "  线程系统启动失败，失败次数:" << m_threadFailureCount;
        qWarning() << "  详细状态:";
        qWarning() << "    GameStateProcessor:" << (m_stateProcessor ? "存在" : "不存在");
        qWarning() << "    RenderThread:" << (m_renderThread ? "存在" : "不存在");

        if (m_threadFailureCount >= MAX_THREAD_FAILURES) {
            qCritical() << "  线程系统多次启动失败，停止游戏";
            emit renderingError("线程系统启动失败，无法继续游戏");
            stopGame();
        }
    }
}

void UnifiedGameRenderer::stopThreads()
{
    if (!m_threadsRunning) {
        return;
    }

    qDebug() << "UnifiedGameRenderer: 停止线程系统";

    // 停止游戏状态处理线程
    if (m_stateProcessor) {
        m_stateProcessor->stop();
        qDebug() << "  游戏状态处理线程已停止";
    }

    // 停止渲染线程
    if (m_renderThread) {
        m_renderThread->stop();
        qDebug() << "  渲染线程已停止";
    }

    m_threadsRunning = false;
    qDebug() << "  线程系统已停止";
}

void UnifiedGameRenderer::updateGameState(const QJsonObject &gameState)
{
    qDebug() << "=== UnifiedGameRenderer::updateGameState ===";
    qDebug() << "消息类型:" << gameState["type"].toString();
    qDebug() << "运行状态 - running:" << m_running << "paused:" << m_paused;
    qDebug() << "组件状态 - processor:" << (m_stateProcessor != nullptr)
             << "threadsRunning:" << m_threadsRunning;

    if (!m_running || m_paused || !m_stateProcessor) {
        qWarning() << "消息被拒绝！原因：基本状态检查失败";
        return;
    }

    // 如果线程未启动，尝试启动（修复启动时序问题）
    if (!m_threadsRunning) {
        qWarning() << "线程未运行，尝试启动线程系统";
        startThreads();

        // 给线程一点启动时间
        QThread::msleep(100);

        if (!m_threadsRunning) {
            qCritical() << "线程启动失败，丢弃消息";
            return;
        }
        qDebug() << "线程启动成功，继续处理消息";
    }

    qDebug() << "消息已接受，发送到处理器";
    // 直接发送到游戏状态处理线程
    m_stateProcessor->addGameState(gameState);
}

void UnifiedGameRenderer::setRenderSize(const QSize &size)
{
    m_config.renderSize = size;

    if (m_renderThread) {
        m_renderThread->setRenderSize(size);
    }

    qDebug() << "UnifiedGameRenderer: 渲染尺寸已更新为" << size;
}

void UnifiedGameRenderer::setRenderConfig(const RenderConfig &config)
{
    m_config = config;

    if (m_renderThread) {
        m_renderThread->setRenderSize(config.renderSize);
        // RenderThread不支持setTargetFPS，FPS由内部管理
    }

    qDebug() << "UnifiedGameRenderer: 渲染配置已更新";
}

void UnifiedGameRenderer::onRenderDataReady(const RenderReadyGameData &data)
{
    // 降噪：每60帧打印一次摘要
    static int readyCount = 0;
    readyCount++;
    if (readyCount % 60 == 1) {
        qDebug() << "*** UnifiedGameRenderer::onRenderDataReady (每60帧摘要) ***";
        qDebug() << "接收实例:" << this;
        qDebug() << "运行状态:" << m_running << "暂停状态:" << m_paused;
        qDebug() << "渲染线程存在:" << (m_renderThread != nullptr);
        qDebug() << "数据有效:" << data.isValid;
        qDebug() << "蛇身长度:" << data.snakeBody.size();
        qDebug() << "食物数量:" << data.foods.size();
        qDebug() << "已有服务器状态:" << m_hasServerState;
    }

    if (!m_running || m_paused || !m_renderThread) {
        qWarning() << "onRenderDataReady: 状态检查失败，丢弃数据";
        return;
    }

    // 检查是否是首帧有效服务器数据
    if (!m_hasServerState && data.isValid && (data.snakeBody.size() > 0 || data.foods.size() > 0)) {
        qint64 firstFrameStartTime = QDateTime::currentMSecsSinceEpoch();
        qDebug() << "*** 首帧落账：收到首帧有效服务器数据 ***";
        qDebug() << "首帧时间戳:" << firstFrameStartTime;
        m_hasServerState = true;

        // 首帧立即落账策略：current = target = serverSnapshot
        RenderReadyGameData firstFrameData = data;
        firstFrameData.timestamp = firstFrameStartTime;

        qDebug() << "首帧服务器数据 - 蛇身长度:" << data.snakeBody.size() << "食物数量:" << data.foods.size();
        qDebug() << "设置hasServerState=true，后续将只渲染服务器数据";
        qDebug() << "*** 首帧立即落账：current=target=serverSnapshot ***";

        // 立即发送到渲染线程并强制更新
        m_renderThread->updateRenderData(firstFrameData);
        m_renderThread->forceImmediateRender();  // 强制立即渲染，不等插值

        // 记录首帧耗时指标
        qint64 firstFrameEndTime = QDateTime::currentMSecsSinceEpoch();
        qint64 firstFrameDuration = firstFrameEndTime - firstFrameStartTime;
        qDebug() << "*** 首帧处理耗时:" << firstFrameDuration << "ms，应立即可见 ***";

        // 发出首帧就绪信号
        emit firstFrameReady(firstFrameDuration);
    }

    if (readyCount % 60 == 1) {
        qDebug() << "*** 发送数据到渲染线程 ***";
    }
    // 发送到渲染线程
    m_renderThread->updateRenderData(data);

    // 诊断：下发后立刻读取快照，验证目标状态是否更新（降噪）
    if (readyCount % 60 == 1) {
        auto snapshot = m_renderThread->getCurrentDataSnapshot();
        qDebug() << "=== 渲染器目标状态诊断 (每60帧摘要) ===";
        qDebug() << "目标动画蛇段数:" << snapshot.snakeBody.size();
        qDebug() << "目标食物数:" << snapshot.foods.size();
        qDebug() << "快照数据有效:" << snapshot.isValid;
        qDebug() << "快照时间戳:" << snapshot.timestamp;
    }

    // 同时也要通知外部（ModernGameController）更新 GameRenderer 的目标状态
    if (readyCount % 60 == 1) {
        qDebug() << "*** 发送 renderDataUpdated 信号到 ModernGameController ***";
    }
    emit renderDataUpdated(data);
    if (readyCount % 60 == 1) {
        qDebug() << "*** renderDataUpdated 信号已发出 ***";
    }
}

void UnifiedGameRenderer::onGameEnded(const QString &reason)
{
    qDebug() << "UnifiedGameRenderer: 游戏结束，原因:" << reason;

    // 停止游戏但保持线程运行，以便处理结束画面
    m_running = false;
    m_paused = false;

    emit gameEnded(reason);
}

void UnifiedGameRenderer::onFrameReady(const QPixmap &frame)
{
    if (!frame.isNull()) {
        // 更新性能统计
        {
            QMutexLocker locker(&m_statsMutex);
            m_stats.processedFrames++;
        }

        emit frameReady(frame);
    }
}

void UnifiedGameRenderer::onPerformanceTimer()
{
    updatePerformanceStats();

    QMutexLocker locker(&m_statsMutex);
    emit fpsChanged(m_stats.currentFPS);
    emit performanceStatsUpdated(m_stats);
}

void UnifiedGameRenderer::updatePerformanceStats()
{
    QMutexLocker locker(&m_statsMutex);

    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 elapsed = currentTime - m_lastStatsUpdate;

    if (elapsed > 0) {
        // 计算FPS
        m_stats.currentFPS = m_stats.processedFrames * 1000 / elapsed;

        // 计算平均帧时间
        if (m_stats.processedFrames > 0) {
            m_stats.avgFrameTime = double(elapsed) / m_stats.processedFrames;
        }

        // 重置计数器
        m_stats.processedFrames = 0;
        m_lastStatsUpdate = currentTime;
    }
}

int UnifiedGameRenderer::currentFPS() const
{
    QMutexLocker locker(&m_statsMutex);
    return m_stats.currentFPS;
}

UnifiedGameRenderer::PerformanceStats UnifiedGameRenderer::getPerformanceStats() const
{
    QMutexLocker locker(&m_statsMutex);
    return m_stats;
}

// 重复的startGame方法已移除

// 重复的stopGame方法已移除

// 重复的pauseGame和resumeGame方法已移除

// 重复的startThreads方法已移除

// 重复的stopThreads方法已移除

// 重复的方法定义已移除

// 重复的setRenderConfig方法已移除

// 重复的onRenderDataReady方法已移除

// 重复的onGameEnded方法已移除

// 重复的onFrameReady方法已移除

// 重复的onPerformanceTimer和updatePerformanceStats方法已移除

// 重复的currentFPS方法已移除

// 重复的getPerformanceStats方法已移除
